<template>
  <el-card class="box-card">
    <div>
      <el-form ref="loginForm" :model="form" :rules="rules" label-width="80px" class="login-box">
        <h3 class="login-title">欢迎登录</h3>
        <el-form-item label="账号" prop="username">
          <el-input type="text" placeholder="请输入账号" v-model="form.username"/>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input type="password" placeholder="请输入密码" v-model="form.password"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">登录</el-button>
          <el-button type="primary" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </el-card>

</template>

<script>
import {Login} from '@/api/login';

export default {
  data() {
    return {
      form: {
        username: '',
        password: '',
      },
      rules: {
        username: [
          {required: true, message: '请输入用户名', trigger: 'blur'},
        ],
        password: [
          {required: true, message: '请输入密码', trigger: 'blur'},
        ]
      },
    };
  },
  methods: {
    handleSubmit() {
      //为表单绑定验证功能
      if(this.form.username === '' || this.form.password === ''){
        this.$message({
          message: '请输入用户名或密码',
          type: 'error'
        });
        return;
      }else{
        Login(this.form).then(response => {
          if (response.data.code === 200) {
            this.$message({
              message: response.data.msg,
              type: 'success'
            });
            // 将token保存到localStorage中
            localStorage.setItem('token', response.data.data);
            //登陆成功，重定向到首页
            this.$router.push('/home');
          } else {
            this.$message({
              message: response.data.msg,
              type: 'error'
            });
          }
        });
      }
    },
    handleReset() {
      this.form = {
        username: '',
        password: '',
      }
    }
  },
};
</script>

<style scoped>.box-card {
  width: 480px;
  margin: auto;
}</style>；